<?php

class AdsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','view'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('delete','list','image'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Ads;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Ads']))
		{
			$model->attributes=$_POST['Ads'];

            $validate=new CUrlValidator();
            if(empty($_POST['Ads']['url'])){
                throw new CHttpException(400,'请设置图片广告链接.');
            }
            if($validate->validateValue($_POST['Ads']['url'])===false){
                throw new CHttpException(400,'请设置正确的链接地址.');
            }

            Yii::import('application.extensions.upload.Upload');
            $Upload = new Upload((isset($_FILES["Ads_img"]) ? $_FILES["Ads_img"] : null));
            $Upload->jpeg_quality  = 100;
            $Upload->no_script     = false;
            $Upload->image_ratio   = true;

            if($_POST['Ads']['cid']==1){
                $Upload->image_resize  = true;
                $_width       = 960;
                $_height       = 285;
            }else if($_POST['Ads']['cid']==2){
                $Upload->image_resize  = true;
                $_width       = 478;
                $_height       = 285;
            }else if($_POST['Ads']['cid']==3){
                $Upload->image_resize  = true;
                $_width       = 960;
                $_height       = 93;
            }else{
                throw new CHttpException(400,'请选择广告分类.');
            }
            $Upload->image_x       = $_width;
            $Upload->image_y       = $_height;

            // some vars
            $newName  = date('YmdHis');
            $destPath = Yii::app()->getBasePath().'/../images/gallery/';
            $destName = '';


            if ($Upload->uploaded) {
                $Upload->file_new_name_body = $newName;
                $Upload->process($destPath);

                // if was processed
                if ($Upload->processed) {
                    $destName = $Upload->file_dst_name;

                    // create the thumb
                    unset($Upload);

                    $Upload = new Upload($destPath.$destName);
                    $Upload->file_new_name_body   = 'thumb_' . $newName;
                    $Upload->no_script            = false;
                    $Upload->image_resize         = true;
                    $Upload->image_x              = $_width/3;
                    $Upload->image_y              = $_height/3;
                    $Upload->image_ratio          = true;
                    $Upload->process($destPath);

                    // write image filename on table
//                    $ad = new Ads();
                    $model->img = $destName;
                    $model->url = $_POST['Ads']['url'];
                    $model->cid = $_POST['Ads']['cid'];
                    $model->title = $_POST['Ads']['title'];
                    $model->type = 0;
                    if($model->save())
                        $this->redirect(array('view','id'=>$model->aid));

                } else {
                    throw new CHttpException(400,$Upload->error);
                }
            } else {
                throw new CHttpException(400,'请选择图片文件.');
            }

//			if($model->save())
            $this->redirect(array('view','id'=>$model->aid));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Ads']))
		{
			$model->attributes=$_POST['Ads'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->aid));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(!Yii::app()->request->isPostRequest)
		{
            $model = $this->loadModel($id);
            $destPath = Yii::app()->getBasePath().'/../images/gallery/';
            @unlink($destPath.$model->img);
            @unlink($destPath.'thumb_'.$model->img);
			// we only allow deletion via POST request
            $model->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $criteria=new CDbCriteria;
        $criteria->condition='type=0';
        $dataProvider=new CActiveDataProvider('Ads',array('criteria'=>$criteria));
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Ads('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Ads']))
			$model->attributes=$_GET['Ads'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Ads::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='ads-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

    public function actionList()
    {
        $criteria=new CDbCriteria;
        $criteria->condition='type=0';
        $dataProvider=new CActiveDataProvider('Ads',array('criteria'=>$criteria));
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }


    public function actionImage()
    {
        $model=Ads::model()->find('type=2');
        if(empty($model)){
            $model = new Ads();
        }
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_FILES['Ads_img']))
        {

            Yii::import('application.extensions.upload.Upload');
            $Upload = new Upload((isset($_FILES["Ads_img"]) ? $_FILES["Ads_img"] : null));
            $Upload->jpeg_quality  = 100;
            $Upload->no_script     = false;
            $Upload->image_ratio   = true;
            $Upload->image_resize  = true;
            $_width= 962;
            $_height=130;
            $Upload->image_x       = $_width;
            $Upload->image_y       = $_height;

            // some vars
            $newName  = date('YmdHis');
            $destPath = Yii::app()->getBasePath().'/../images/gallery/';
            @unlink($destPath.$model->img);
            @unlink($destPath.'thumb_'.$model->img);

            $destName = '';

            if ($Upload->uploaded) {
                $Upload->file_new_name_body = $newName;
                $Upload->process($destPath);

                // if was processed
                if ($Upload->processed) {
                    $destName = $Upload->file_dst_name;

                    // create the thumb
                    unset($Upload);

                    $Upload = new Upload($destPath.$destName);
                    $Upload->file_new_name_body   = 'thumb_' . $newName;
                    $Upload->no_script            = false;
                    $Upload->image_resize         = true;
                    $Upload->image_x              = $_width/2;
                    $Upload->image_y              = $_height/2;
                    $Upload->image_ratio          = true;
                    $Upload->process($destPath);

                    // write image filename on table
//                    $ad = new Ads();
                    $model->img = $destName;
                    $model->url = Yii::app()->user->id;
                    $model->cid = 0;
                    $model->title = '首页横幅';
                    $model->type = 2;
                    $model->order = 0;
                    $model->save();
                } else {
                    throw new CHttpException(400,$Upload->error);
                }
            } else {
                throw new CHttpException(400,'请选择图片文件.');
            }

//			if($model->save())
//            $this->redirect(array('image','model'=>$model->aid));
        }

        $this->render('image',array(
            'model'=>$model,
        ));
    }
}
